using System;
using System.IO;
using System.Web;
using System.Data;
using System.Xml;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Web.Security;
using System.Web.Services;
using ACM.cmsarea08;
using ACM.cmsarea08.Provider;
using System.Web.SessionState;


namespace ACM.cmsarea08.Core {
	public class StatusHandler :  IHttpAsyncHandler { //IHttpAsyncHandler IHttpHandler
			
		public bool IsReusable { get { return true; } }
//		
        public void ProcessRequest(System.Web.HttpContext contesto)
        {
        	// non usato
		}
		  public IAsyncResult BeginProcessRequest(HttpContext ctx, AsyncCallback cb, object obj)
		  {
		    AsyncStatusState reqState = new AsyncStatusState(ctx, cb, obj);
		    AsyncStatusHandlerRequest ar = new AsyncStatusHandlerRequest(reqState);
		    ThreadStart ts = new ThreadStart(ar.ProcessRequest);
		    Thread t = new Thread(ts);
		    t.Start();
		    return reqState;
		  }
	        
		  public void EndProcessRequest(IAsyncResult ar)
		  {
		    AsyncStatusState ars = ar as AsyncStatusState;
		    if (ars != null)
		    {
		     // Clean Up
		    }
		  }      
        
        
        
	}

	public class AsyncStatusState : IAsyncResult {
		
		internal HttpContext _ctx;
		internal AsyncCallback _cb;
		internal object _dati;
		private bool _iscompleted = false;
		private ManualResetEvent _callCompleteEvent = null;
		
		public AsyncStatusState(HttpContext ctx, AsyncCallback cb, object dati) {
			_ctx = ctx;
			_cb = cb;
			_dati = dati;
			
		}
		internal void CompleteRequest() {
			_iscompleted = true;
			lock(this) {
				if(_callCompleteEvent!=null) {
					_callCompleteEvent.Set();
				}
				 if (_cb != null)
				 	_cb(this);
			}
		}
		public object AsyncState {
			get { return _dati; }
		}
		public bool CompletedSynchronously {
			get { return false; }
		}
		public bool IsCompleted            {
			get { return _iscompleted; }
		}
		public WaitHandle AsyncWaitHandle {
			get {
				lock(this) {
					if(_callCompleteEvent == null) 
						_callCompleteEvent = new ManualResetEvent(false);
					return _callCompleteEvent;
				}
			}
		}



	}
	class AsyncStatusHandlerRequest : IRequiresSessionState
	{

	  private AsyncStatusState _asyncRequestState;
	
	  public AsyncStatusHandlerRequest(AsyncStatusState ars)
	  {
	    _asyncRequestState = ars;
	  }
	    
	  
	  public void ProcessRequest()
	  {
        	string name = "";
        	string q = "";
        	if(_asyncRequestState._ctx.Request.QueryString["name"]==null) {
        		StoreResponse("NO NAME");
        		return;
        	}
        	name = _asyncRequestState._ctx.Request.QueryString["name"].ToString();
        	if(name.Trim().Length==0) {
        		StoreResponse("NO NAME");
        		return;        		
        	}

        	if(_asyncRequestState._ctx.Request.QueryString["q"]==null) {
        		StoreResponse("NO q");
        		return;
        	}
        	q = _asyncRequestState._ctx.Request.QueryString["q"].ToString();
        	if(q.Trim().Length==0) {
        		StoreResponse("NO q");
        		return;        		
        	} else
        		q = HttpUtility.UrlDecode(q);
        	
        	if(_asyncRequestState._ctx==null) {
        		StoreResponse("NO CONTEXT");
        		return;        		
        	}
			if(_asyncRequestState._ctx.Session == null) {
				StoreResponse("NO SESSION");
        		return;
			}
        	
			if(_asyncRequestState._ctx.Session[ "dummy" ] == null) {
				StoreResponse("NO SESSION_DUMMY");
        		return;
			}
			
        	if(name!=_asyncRequestState._ctx.Session.SessionID) {
				StoreResponse( "NO VALID");
        		return;        		
        	}
			
			try {
				ACM.cmsarea08.Provider.StatusEvent testEvent = new ACM.cmsarea08.Provider.StatusEvent(
	                              q, 
	                              this, 
	                              System.Web.Management.WebEventCodes.WebExtendedBase + 1);
				testEvent.Raise();		
			} catch(Exception ex) {
				StoreResponse(ex.ToString());
        		return;				
			}
			
			StoreResponse("OK");

	  	//finito.
	    _asyncRequestState.CompleteRequest();
	  }
	  private void StoreResponse(string message) {
    	_asyncRequestState._ctx.Response.ContentType = "text/html";
    	_asyncRequestState._ctx.Response.Write(message);
        _asyncRequestState._ctx.Response.End();        	
      }	  
 	  
	}
	
	
}
